<template>
  <rx-dialog style="height: 100%;" @handOk="onOk" @cancel="cancel">
      <rx-layout>
          <div slot="center">
              <a-form  :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">

                  <a-form-item  :label="i18n('list.formSolution','表单方案')">
                      <rx-input-button v-model="dialogVal"
                                       @click="selectFormSolution"
                                       style='width: 300px;'
                      >
                      </rx-input-button>
                  </a-form-item>
                  <a-form-item  :label="i18n('formDialog.readonly','是否只读')">
                      <a-radio-group v-model="openFormConfig.readonly"
                                     :options="readonlyArr"

                                    >
                      </a-radio-group>
                  </a-form-item>
                  <a-form-item  :label="i18n('formDialog.dataMap','数据映射')">
                      <a-radio-group name="mappingType"
                                     v-model="openFormConfig.mappingType"
                                     :options="mappingTypeArr"  @change="changeMappingType">

                      </a-radio-group>
                  </a-form-item>
                  <a-form-item  :label="i18n('formDialog.bindTable','绑定表')"   v-if="  openFormConfig.mappingType=='subParam' || openFormConfig.mappingType=='mainParam' ">
                      <a-select style="width: 150px;margin-right: 10px"
                                v-model="openFormConfig.boEntityAlias"
                                :getPopupContainer="p=>p.parentNode"
                                @change="changeBoEntity"
                                :options="boEntity"
                                allowClear>

                      </a-select>
                  </a-form-item>
                  <a-form-item :label="i18n('customDialog.callbackmethod','回调方法')" >
                      <a-input :placeholder="i18n('formDialog.callMethodDesc','请输入回调函数名称,参数为')+ '(action,data)'" v-model="openFormConfig.callbackMethod" style='width: 300px;' />
                  </a-form-item>
                  <a-form-item :label="i18n2('form.listSize','弹窗大小')">
                      <a-radio-group :placeholder="i18n2('form.listSize','列表大小')" v-model="openFormConfig.isMax">
                          <a-radio value="YES">{{i18n2('form.fullScreen','全屏')}}</a-radio>
                          <a-radio value="NO">{{i18n2('form.customSize','自定义大小')}}</a-radio>
                      </a-radio-group>
                  </a-form-item>
                  <a-row v-if="openFormConfig.isMax=='NO'">
                      <a-col :span="12">
                          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"  :label="i18n2('form.width','宽度')">
                              <a-input-number :placeholder="i18n2('form.width','宽度')" v-model="openFormConfig.width" :min="100" :max="1500"/>
                          </a-form-item>
                      </a-col>
                      <a-col :span="12">
                          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"  :label="i18n2('form.height','高度')">
                              <a-input-number :placeholder="i18n2('form.height','高度')" v-model="openFormConfig.height" :min="100" :max="1500"/>
                          </a-form-item>
                      </a-col>
                  </a-row>


                  <a-form-item :label="i18n('formDialog.bindField','绑定字段')"  >

                      <div style="text-align: right;" v-if="openFormConfig.mappingType!='pk'">
                          <a-button-group>
                              <a-button @click="addField" type="primary" >
                                  <a-icon type="plus"></a-icon>
                              </a-button>
                              <a-button @click="removeFields">
                                  <a-icon type="minus"></a-icon>
                              </a-button>

                          </a-button-group>
                      </div>

                      <a-table :dataSource="openFormConfig.returnFields" :pagination="false"
                               :rowSelection="rowSelection"
                               rowKey="idx_">
                          <a-table-column :title="i18n('formDialog.formField','表单字段')" dataIndex="bindFieldLabel" width="150px">
                              <template slot-scope="text, record">

                                  <a-form-item v-if=" openFormConfig.mappingType=='pk' || openFormConfig.mappingType=='noPk'"
                                      class="tableItems">
                                      {{record.bindFieldLabel}}
                                  </a-form-item>
                                  <a-form-item v-else-if=" openFormConfig.mappingType=='mainParam' || openFormConfig.mappingType=='subParam'"
                                               class="tableItems">

                                      <a-select style="width: 100%;" :placeholder="i18n('customDialog.text','文本')"
                                                v-model="record.bindField"
                                                :options="tableFields"
                                                :getPopupContainer="p=>p.parentNode" allowClear
                                                @change="changeField($event,record)"
                                      >
                                      </a-select>
                                  </a-form-item>
                              </template>
                          </a-table-column>
                          <a-table-column title="映射字段" dataIndex="returnField" width="300px">
                              <template slot-scope="text, record">
                                  <a-row v-if="record.valmode=='double'">
                                      <a-col :span="12">
                                          <a-form-item
                                              :label="i18n('customDialog.text','文本')"
                                              :labelCol="{span:6}"
                                              :wrapperCol="{span:15}"
                                              class="tableItems">
                                              <a-select style="width: 100%;" :placeholder="i18n('customDialog.text','文本')"
                                                        v-model="record.returnLabel"
                                                        :options="headerFields"
                                                        :getPopupContainer="p=>p.parentNode" allowClear>
                                              </a-select>
                                          </a-form-item>
                                      </a-col>
                                      <a-col :span="12">
                                          <a-form-item
                                              :label="i18n('customDialog.value','值')"
                                              :labelCol="{span:6}"
                                              :wrapperCol="{span:15}"
                                              class="tableItems">
                                              <a-select style="width: 150px;" :placeholder="i18n('customDialog.value','值')"
                                                        v-model="record.returnValue"
                                                        :options="headerFields"
                                                        :getPopupContainer="p=>p.parentNode" allowClear>
                                              </a-select>
                                          </a-form-item>
                                      </a-col>
                                  </a-row>
                                 <a-form-item v-else
                                               class="tableItems">
                                      <a-select style="width: 150px;"
                                                v-model="record.returnValue"
                                                :defaultValue="record.returnValue"
                                                :options="headerFields"
                                                :getPopupContainer="p=>p.parentNode" allowClear>
                                      </a-select>
                                  </a-form-item>
                              </template>
                          </a-table-column>
                      </a-table>
                  </a-form-item>
              </a-form>
          </div>
      </rx-layout>
  </rx-dialog>
</template>

<script>
    import Vue from 'vue'
    import {RxDialog, Util,FormBoListPreview,PublicFunction,GridMixin} from "@lowcode/jpaas-common-lib";
    import FormBoListExt from "./FormBoListExt";
    import DialogBox from "@/assets/js/DialogBox";
   // import FormPcApi from '@/components/api/formPc.js';
    import FormBoAttrApi from "@/api/form/bo/formBoAttr";
    import FormBoEntityApi from "@/api/form/bo/formBoEntity";
    import FormBoListApi from "@/api/form/core/formBoList";
    import FormSolutionApi from "@/api/form/core/formSolution";

  export default {
    name:"FormBoListConfigOpenFormDialog",
    mixins: [GridMixin],
    props: {
        layerid: { type: String },
        lydata: {type: Object },
        destroy: Function,
        //列表主键
        pkId:{type: String},
        //表单配置信息
        formConfig:{
            type: String
        },
        config:{
            type: Object
        },
    },
    data(){
      return {
          labelCol: {span: 8},
          wrapperCol: {span: 16},
          boEntityShow:false,
          dialogVal:"",
          openFormConfig: {
              pkId:"",
              formAlias: "",//表单方案alias
              formName:"",//表单方案名称
              boDefId:"",//boDefId
              mappingType:"",//数据映射
              boEntityAlias:"",//绑定控件
              boEntityName:"",//
              gridName:"main",//表名
              curtype:"main",//main""onetoone",
              //回调方法
              callbackMethod:'',
              //是否只读
              readonly:false,
              /*{
                  returnLabel: "FXK",
                  returnValue: "FXKLB",
                  returnField: "",
                  bindField: "user",
                  bindFieldLabel : "用户",
                  valmode: "single",
                  ctltype: "rx-user",
                  idx_: "nsprmsm786965"
              }*/
              returnFields:[],
              //窗口大小
              isMax:"YES",
              height:600,
              width:800

          },
          readonlyType:[
              {value: 'pk', label: this.i18n('formDialog.pkMap','主键映射')},
          ],
          notReadType:[
              {value: 'pk', label: this.i18n('formDialog.pkMap','主键映射')},
              {value: 'mainParam', label: this.i18n('formDialog.mainParam','主表数据绑定')},
              {value: 'subParam', label: this.i18n('formDialog.subParam','子表数据绑定')},
          ],

          mappingTypeArr: [
              {value: 'mainParam', label: this.i18n('formDialog.mainParam','主表数据绑定')},
              {value: 'subParam', label: this.i18n('formDialog.subParam','子表数据绑定')},
          ],
          readonlyArr:[
              {value: true, label: this.i18n('formDialog.yes','是')},
              {value: false, label: this.i18n('formDialog.no','否')},
          ],
          //数据绑定列表
          /*returnFields: [
              /!*{
                  returnLabel: "FXK",
                  returnValue: "FXKLB",
                  returnField: "",
                  bindField: "user",
                  bindFieldLabel : "用户",
                  valmode: "1",
                  ctltype: "rx-user",
                  idx_: "nsprmsm786965"
              }*!/
          ],*/
          boEntity:[],
          mainBoEntity:[],
          subBoEntity:[],
          fieldData: {},
          selectFormSolutionData:{},
          headerFields:[],
          selectedRowKeys: [],
          //某个实体的字段
          tableFields:[]
      }
    },
    created() {
      this.load();
    },
    computed:{
        rowSelection() {
            return {
                selectedRowKeys: this.selectedRowKeys,
                onChange: this.onSelectChange
            }
        },
    },
    methods:{
        i18n(name,text,key){
            return this.$ti18(name,text,"formBoList",key);
        },
        i18n2(name, text, key) {
            return this.$ti18(name, text, "formBoListDialog", key);
        },
        load(){

            let formConfig = {};
            if(this.formConfig){
                formConfig = JSON.parse(this.formConfig);
                //合并对象
                Object.assign(this.openFormConfig,formConfig);
            }

            //回显表单方案字段
            this.dialogVal = JSON.stringify({text: this.openFormConfig.formName, value: this.openFormConfig.bodefId})
            //加载列头信息
            this.reloadColumns();
            //加载formSolution信息
            if(formConfig.pkId){
                this.getFormSolution(formConfig.pkId);
            }
            //加载BoEntity信息
            if(formConfig.boDefId){
                let self_ = this;
                this.queryToBoEntity(formConfig.boDefId,function (){
                    if(self_.openFormConfig.mappingType){
                        self_.handleBoEntity(self_.openFormConfig.mappingType,self_.openFormConfig.boEntityAlias,self_.openFormConfig.boEntityName)
                    }
                });
            }

        },
        /**
         * 选择表单方案
         */
        selectFormSolution() {
            let confSol = {curVm: this, widthHeight: ['800px', '600px'], data: {multiSelect: false}};
            let self_ = this;
            DialogBox.openSoution(confSol, function (data) {
                self_.selectFormSolutionData = data;
                //更新配置数据
                let config= {
                    pkId:data.pkId,
                    formAlias: data.alias,//表单方案alias
                    formName:data.name,//表单方案名称
                    boDefId:data.bodefId,//boDefId
                    mappingType:"",//数据映射
                    boEntityAlias:"",//绑定控件
                    boEntityName:"",//
                    curtype:"",
                    callbackMethod:"",
                    returnFields:[]
                }
                self_.openFormConfig = Object.assign(self_.openFormConfig,config);
                //回显表单方案字段
                self_.dialogVal = JSON.stringify({text: data.name, value: data.bodefId})
                self_.queryToBoEntity(data.bodefId)

                //self_.setForm(config, data.bodefId,row);

            })
        },
        getFormSolution(pkId){
            let self_ = this;
             FormSolutionApi.get(pkId).then(res => {
                 self_.selectFormSolutionData = res.data;
             });

        },
        //查询boEntity实体
        queryToBoEntity(boDefId,callback){
            let self_ = this;
            FormBoAttrApi.queryToBoEntity(boDefId).then(res=>{
                self_.mainBoEntity =[];
                self_.subBoEntity =[];
                for(let i=0;i<res.length;i++){
                    res[i].label = res[i].name;
                    res[i].value = res[i].alias
                    if("main"==res[i].boRelation.type){
                        res[i].label = this.i18n('form.tableMaster','主表');
                        self_.mainBoEntity.push( res[i]);
                    }else{
                        self_.subBoEntity.push( res[i]);
                    }
                    self_.fieldData[res[i].alias] = [];
                    self_.loadBoAttrs(boDefId, res[i].alias,  true) ;

                }
                if(callback){
                    callback();
                }

            });

        },
        //查询boAttrs实体
        loadBoAttrs(boDefId, alias) {
            let self = this;
            FormBoEntityApi.getFieldByBoDefId(boDefId, alias,true).then(data => {
                let fields=data.map(item=>{
                    let name=item.name;
                    if(item.control=='rx-commonfield' || item.isPk==1){
                        name=item.fieldName;
                    }
                    return {value:name,label:item.comment,valmode:item.isSingle?"single":"double",ctltype:item.control};
                });
                self.fieldData[alias].push(...fields);
            })
        },
        changeBoEntity(value){
            let currData = {};
            for(let i=0;i<this.boEntity.length;i++){
                if(this.boEntity[i].value==value){
                    currData = this.boEntity[i];
                }
            }
            this.openFormConfig.curtype = currData.boRelation.type;
            if("main"==currData.boRelation.type){
                this.openFormConfig.gridName = "main";
            }else{
                this.openFormConfig.gridName = currData.alias;
            }
            //表字段
            this.tableFields = this.fieldData[value];

        },
        //设置绑定列表数据
        setReturnFields(){

            this.openFormConfig.returnFields = [];
            let mappingType = this.openFormConfig.mappingType;

            if("pk"==mappingType){
                //主键绑定数据列表
                this.openFormConfig.returnFields.push(this.handleReturnFields("ID_","主键","1","rx-textbox"));
            }else if("noPk"==mappingType){
                //无组件绑定数据列表
                let noPkSetting ={} ;
                if(this.selectFormSolutionData.noPkSetting){
                    noPkSetting = JSON.parse(this.selectFormSolutionData.noPkSetting);
                }

                //[{"name":"CREATE_BY_","valueSource":"param","valueDef":"[USERID]","idx_":"ztbnrup732912","edit":{"field":false,"from":true,"setting":true}}]
                for(let j=0;j<noPkSetting.length;j++){
                    let item =  noPkSetting[j];
                    if(item.valueSource=="param"){
                        this.openFormConfig.returnFields.push(this.handleReturnFields(item.name,item.name,1,""));
                    }
                }

            }
        },
        //处理bo列表对象
        handleBoEntity(mappingType,boEntityAlias,boEntityName){
            if("pk"==mappingType || "noPk"==mappingType || "mainParam"==mappingType){
                this.boEntity = this.mainBoEntity;
                this.openFormConfig.boEntityAlias = boEntityAlias?boEntityAlias:this.mainBoEntity[0].alias;
                this.openFormConfig.boEntityName = boEntityName?boEntityName:this.mainBoEntity[0].name;

            }else if("subParam"==mappingType){
                this.boEntity = this.subBoEntity;
                this.openFormConfig.boEntityAlias = boEntityAlias?boEntityAlias:this.subBoEntity[0].alias;
                this.openFormConfig.boEntityName = boEntityName?boEntityName:this.subBoEntity[0].name;
            }
            this.tableFields=this.fieldData[ this.openFormConfig.boEntityAlias];
        },
        //处理绑定对象
        handleReturnFields(bindField,bindFieldLabel,isSingle,control){
            /*{
             "returnLabel": "FXK",
             "returnValue": "FXKLB",
             "returnField": "",
             "bindField": "user",
             "bindFieldLabel" : "用户",
             "valmode": "double",
             "ctltype": "rx-user",
             "idx_": "nsprmsm786965"
         }*/
            let obj = {};
            obj.returnLabel= '';
            obj.returnValue= '';
            obj.returnField= '';
            obj.bindField= bindField;
            obj.bindFieldLabel = bindFieldLabel
            if(isSingle==0){
                obj.valmode= "double";
            }else{
                obj.valmode= "single";
            }
            obj.ctltype= control;
            obj.idx_= Util.randomId();
            return obj;
        },
        reloadColumns() {
            let self_ = this;

            FormSolutionApi.getColumnsbyAlias(this.config.alias).then(res=>{
                self_.headerFields =res.data.map(function (item) {
                    console.log(item.FIELD_NAME_)
                    item.value=item.FIELD_NAME_;
                    item.label=item.COMMENT_;
                    return item
                });
                self_.$forceUpdate();
            })
        },
        //切换数据映射单选框
        changeMappingType(){
            let mappingType = this.openFormConfig.mappingType;

            if(mappingType){
                this.handleBoEntity(mappingType);
                this.changeBoEntity(this.openFormConfig.boEntityAlias);
                this.setReturnFields()
            }

        },

        onOk(){
            Util.closeWindow(this,"ok",this.openFormConfig);
        },
        cancel(){
            Util.closeWindow(this,"cancel");
        },

        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys;
        },
        addField(){
            let obj=this.handleReturnFields("","",1,"");
            this.openFormConfig.returnFields.push(obj);
        },
        removeFields() {
            this.removeRows(this.openFormConfig.returnFields, this.selectedRowKeys);
        },
        changeField(val,record){
            var ary=this.tableFields.filter(item=>item.value==val);
            if(ary && ary.length>0){
                record.valmode=ary[0].valmode;
                record.ctltype=ary[0].ctltype;
            }
        }
    },

  }
</script>

<style scoped>

</style>
